<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      stripe
      fit
    >
      <el-table-column align="center" label="名称" width="200" prop="name">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdateUser(scope.row)">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" width="200" prop="remark"/>
      <el-table-column label="创建时间" width="250" align="center" prop="insert_tms"/>
      <el-table-column label="最后更新时间" width="250" align="center" prop="update_tms"/>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleViewOrEdit(scope.row, 'view')">查看</el-button>
          <el-button type="text" size="small" @click="handleViewOrEdit(scope.row, 'update')">编辑</el-button>
          <el-button type="text" size="small" @click="handlePermit(scope.row)">授权</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination v-show="total>0" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.page_size" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]" >
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" :disabled="isView"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" :disabled="isView"/>
        </el-form-item>
      </el-form>
      <div v-if="!isView" slot="footer" cslass="dialog-footer">
        <el-button v-waves @click="cancel">取 消</el-button>
        <el-button v-waves @click="reset">重 置</el-button>
        <el-button v-waves :loading="submitFormLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, add, update, del } from '@/api/role'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20
      },
      total: null,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        view: '查看',
        update: '编辑',
        create: '新增'
      },
      form: {
        id: null,
        name: null,
        remark: null
      },
      isView: false,
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '长度在 500 个字符以内', trigger: 'blur' }
        ]
      },
      submitFormLoading: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 换页
    handleSizeChange(val) {
      this.listQuery.page_size = val
      this.fetchData()
    },
    // 修改每页page_size
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    // 弹出新建弹框
    handleCreate() {
      this.dialogFormVisible = true
      this.resetForm()
      this.dialogStatus = 'create'
    },
    reset() {
      this.resetForm(this.form.id)
    },
    // 重置弹框表单
    resetForm(oldId) {
      this.form = {
        id: oldId,
        name: null,
        remark: null
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    cancel() {
      this.dialogFormVisible = false
      this.resetForm()
    },
    submitForm() {
      this.submitFormLoading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            update(this.form).then(response => {
              this.fetchData()
              this.submitFormLoading = false
              this.dialogFormVisible = false
            }).catch(() => {
              this.submitFormLoading = false
            })
          } else {
            add(this.form).then(response => {
              this.fetchData()
              this.submitFormLoading = false
              this.dialogFormVisible = false
            }).catch(() => {
              this.submitFormLoading = false
            })
          }
        } else {
          console.log('error submit!!')
          this.submitFormLoading = false
          return false
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id: row.id }).then(response => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: `删除成功，删除了ID为${row.id}的数据`
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 弹出查看或者编辑弹框
    handleViewOrEdit(row, handleType) {
      this.form = Object.assign({}, row)
      this.dialogStatus = handleType
      this.isView = handleType === 'view'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 给角色添加用户
    handleUpdateUser(row) {
      // this.$router.push({ path: 'register', query: { plan: 'private' }})
      this.$router.push({ name: 'RoleUser', params: { roleId: 123 }})
    },
    // 授权
    handlePermit(row) {
      this.$router.push({ name: 'Permit', params: { roleId: 123 }})
    }
  }
}
</script>
